package io.eyer.rpc.codec;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import io.eyer.nio.core.codec.Codec;

/**
 * Created by Administrator on 2015/8/31.
 */
public class KeyoCodec implements Codec {

    static Kryo kryo = new Kryo();
    @Override
    public byte[] encode(Object obj) {
        return this.kryoSerizlize(obj);
    }

    @Override
    public Object decode(byte[] bytes) {
        return this.kryoUnSerizlize(bytes);
    }

    public static byte[] kryoSerizlize(Object obj) {
        Kryo kryo = new Kryo();
        byte[] buffer = new byte[2048];
        try (
                Output output = new Output(buffer);
        ) {

            kryo.writeClassAndObject(output, obj);
            return output.toBytes();
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public static Object kryoUnSerizlize(byte[] src) {
        try (
                Input input = new Input(src);
        ) {
            return kryo.readClassAndObject(input);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
